
import os

from flask import Blueprint, request, jsonify, render_template

from applications.common.utils.http import table_api, success_api, fail_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import str_escape
from applications.extensions import db
from mod.fun import tconf, cache_file
from plugins.users.mod.fun import parse_fullname
from plugins.users.models.User import User

dir_path = os.path.dirname(os.path.realpath(__file__)).replace("\\", "/")

bp = Blueprint('users_admin', __name__, url_prefix='/admin')

@bp.route('/', methods=['GET'])
@authorize('users:admin:index')
def index():
    return render_template('admin/index/index.html')

@bp.route('/data', methods=['GET', 'POST'])
@authorize('users:admin:index')
def data():
    # 读取用户数据
    truename = str_escape(request.args.get('truename', type=str))
    username = str_escape(request.args.get('username', type=str))
    filter = []
    if truename:
        filter.append(User.truename.contains(truename))
    if username:
        filter.append(User.username.contains(username))
    query = db.session.query(User).filter(*filter).layui_paginate()
    rt = []
    for u in query.items:
        rt.append({
            'id': u.id,
            'truename': u.truename,
            'username': u.username,
            'email': u.email,
            'mobile': u.mobile,
            'status': u.status
        })
    return table_api(data=rt, count=query.total)

@bp.route('/add', methods=['POST', 'GET'])
@authorize('users:admin:add')
def add():
    if request.method == 'POST':
        data = request.form
        truename = data.get('truename')
        u = parse_fullname(truename)
        user = User(
            username=data.get('username'),
            truename=data.get('truename'),
            email=data.get('email'),
            mobile=data.get('mobile'),
            usertype=data.get('usertype'),
            idcard = data.get('idcard'),
            cardid = data.get('cardid'),
            pinyin = u['pinyin'],
            py = u['py'],
            regip = request.remote_addr

        )
        user.set_password(data.get('password'))
        db.session.add(user)
        db.session.commit()
        return success_api(msg='添加成功')

    else:
        return render_template('admin/index/add.html')

@bp.route('/edit', methods=['POST', 'GET'])
@authorize('users:admin:edit')
def edit():
    if request.method == 'POST':
        id = request.args.get('id', type=int)
        if id:
            data = request.form
            user = User.query.get(id)
            if user:
                user.truename = data.get('truename')
                user.email = data.get('email')
                user.mobile = data.get('mobile')
                user.usertype = data.get('usertype')
                user.idcard = data.get('idcard')
                user.cardid = data.get('cardid')
                db.session.commit()
                return success_api(msg='修改成功')
            else:
                return fail_api(msg='用户不存在')
        else:
            return fail_api(msg='参数错误！')
    else:
        id = request.args.get('id', type=int)
        if id:
            user = User.query.get(id)
            return render_template('admin/index/edit.html', u=user)

@bp.route('/remove', methods=['POST', 'GET'])
@authorize('users:admin:remove')
def remove():
    id = request.form.get('id', type=int)
    if id:
        db.session.query(User).filter(User.id == id).delete()
        db.session.commit()
        return success_api(msg='删除成功')
    return fail_api(msg='删除失败')


@bp.route('/ajax_get_items', methods=['POST', 'GET'])
def ajax_get_items():
    if request.method == 'POST':
        item = request.form.get('item', type=str)
    else:
        item = request.args.get('item', type=str)
    if item == 'usertype':
        conf = tconf('users','usertype')
        return success_api(conf)
    elif item == 'userxmselect':
        d = cache_file('userxmselect')
        if d:
            # print('cache')
            return jsonify(d)
        else:
            d = User.query.with_entities(User.id,User.username,User.truename).all()
            if d:
                # print('database')
                data = []
                for da in d:
                    data.append({
                        'value': da.id,
                        'name': da.username,
                        'showname': da.truename + '(' + da.username + ')'
                    })
                cache_file('userxmselect', data)
                return jsonify(data)
            else:
                return fail_api(msg='没有数据')